package team.kirohuji.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import team.kirohuji.shiro.credentials.RetryLimitHashedCredentialsMatcher;
import team.kirohuji.shiro.filter.JWTFilter;
import team.kirohuji.shiro.realm.DefaultModularRealm;
import team.kirohuji.shiro.realm.TokenRealm;
import team.kirohuji.shiro.realm.UserRealm;

@Configuration
public class ShiroConfig {

    @Bean("securityManager")
    public DefaultWebSecurityManager getManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 使用自己的realm
/*        manager.setRealm(userRealm());*/
        manager.setAuthenticator(defineModularRealmAuthenticator());
        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        manager.setSubjectDAO(subjectDAO);

        return manager;
    }
    @Bean
    public DefaultModularRealm defineModularRealmAuthenticator() {
    	DefaultModularRealm dmr=new DefaultModularRealm();
    	Map<String,Realm> definedRealms=new HashMap<>();
    	definedRealms.put("userRealm", userRealm());
    	definedRealms.put("tokenRealm", tokenRealm());
    	dmr.setDefinedRealms(definedRealms);
    	dmr.setAuthenticationStrategy(new FirstSuccessfulStrategy());
    	return dmr;
    }
  //缓存管理器
  	@Bean
  	public CacheManager cacheManager() {
          EhCacheManager cacheManager = new EhCacheManager();
          cacheManager.setCacheManagerConfigFile("classpath:encache.xml");
  		return cacheManager;
  	}
      //凭证匹配器
  	@Bean
  	public CredentialsMatcher credentialsMatcher() {
  		RetryLimitHashedCredentialsMatcher rlcm = new RetryLimitHashedCredentialsMatcher(cacheManager());
  		rlcm.setHashAlgorithmName("md5");
  		rlcm.setHashIterations(252);
  		rlcm.setStoredCredentialsHexEncoded(true);
  		return rlcm;
  	}
  	@Bean
  	public Realm userRealm() {
  		UserRealm userRealm = new UserRealm();
  		userRealm.setCredentialsMatcher(credentialsMatcher());
  		userRealm.setCachingEnabled(false);
  		userRealm.setAuthenticationCachingEnabled(true);
  		userRealm.setAuthenticationCacheName("authenticationCache");
  		userRealm.setAuthorizationCacheName("authorizationCache");
  		userRealm.setAuthorizationCachingEnabled(true);
  		return userRealm;
  	}
  	@Bean
  	public Realm tokenRealm() {
  		TokenRealm tokenRealm = new TokenRealm();
  		return tokenRealm;
  	}
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        // 添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JWTFilter());
        factoryBean.setFilters(filterMap);

        factoryBean.setSecurityManager(securityManager);
        factoryBean.setUnauthorizedUrl("/401");

        /*
         * 自定义url规则
         * http://shiro.apache.org/web.html#urls-
         */
        Map<String, String> filterRuleMap = new HashMap<>();
        // 所有请求通过我们自己的JWT Filter
        filterRuleMap.put("/sign/in", "anon");
        filterRuleMap.put("/**", "jwt");
        // 访问401和404页面不通过我们的Filter
        filterRuleMap.put("/401", "anon");
        
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    /**
     * 下面的代码是添加注解支持
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
